package com.swak.frame.exception;

import java.util.ArrayList;
import java.util.List;

import com.swak.frame.dto.base.RestApiCode;

/**
 * 
 * ClassName: ExceptionUtil.java 
 * @Description: ApiException
 * @author colley.ma
 * @date 2021年3月15日
 */
public final class ApiExceptionUtil {
	public static void throwException(String e) throws ApiException {
		throw new ApiException(e);
	}

	public static void throwException(Throwable e) throws ApiException {
		throw new ApiException(e);
	}

	public static void throwException(String er, Throwable e) throws ApiException {
		throw new ApiException(er, e);
	}

	public static void throwException(RestApiCode apiCodeEnum) throws ApiException {
		throw new ApiException(apiCodeEnum);
	}

	public static void throwException(RestApiCode apiCodeEnum, Throwable e) throws ApiException {
		throw new ApiException(apiCodeEnum, e);
	}
	
	public static void throwException(RestApiCode apiCodeEnum, String er) throws ApiException {
		throw new ApiException(apiCodeEnum, er);
	}

	public static void throwException(RestApiCode apiCodeEnum, String er, Throwable e) throws ApiException {
		throw new ApiException(apiCodeEnum, er, e);
	}
	
	public static void throwException(String retCode, String er) throws ApiException{
		throw new ApiException(retCode,er);
	}
	

	public static String getExceptionStackTrace(Throwable e) {
		StringBuffer sb = new StringBuffer();
		sb.append(e);

		StackTraceElement[] trace = e.getStackTrace();

		for (int i = 0; i < trace.length; i++) {
			sb.append("\n " + trace[i]);
		}

		Throwable ourCause = e.getCause();

		if (ourCause != null) {
			getCauseStackTrace(sb, ourCause);
		}

		return sb.toString();
	}
	


	public static Throwable getRootCase(Throwable a) {
		Throwable r = null;

		for (r = a; r.getCause() != null; r = r.getCause()) {
			;
		}

		return r;
	}

	private static void getCauseStackTrace(StringBuffer sb, Throwable cause) {
		if (null != cause) {
			StackTraceElement[] trace = cause.getStackTrace();

			for (int i = 0; i < trace.length; i++) {
				sb.append("\n " + trace[i]);
			}

			Throwable ourCause = cause.getCause();

			if (ourCause != null) {
				getCauseStackTrace(sb, ourCause);
			}
		}
	}
	
	
	private static  void getCauseStackTrace(List<String> list, Throwable cause) {
		if (null != cause) {
			list.add(cause.getClass().getName());
			getCauseStackTrace(list, cause.getCause());
		}
	}
	
	public static  List<String> getCauseExceptionName(Throwable cause){
		List<String> list = new ArrayList<String>();
		getCauseStackTrace(list, cause);
		return list;
	}
	
	
	public static boolean isContains(Throwable cause,String exceptionName) {
		List<String> exceptionNameList = getCauseExceptionName(cause);
		return exceptionNameList.contains(exceptionName);
	}

	
}
